package com.cofdet.modbusdebugger;


import android.content.Intent;
import android.util.Log;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.ByteBuffer;

import static android.system.OsConstants.IPPROTO_TCP;


public class TcpClient implements Runnable{
    private String TAG = "TcpClient";
    private final String  serverIP;
    private int serverPort = 10001;
    private OutputStream os = null;
    private InputStream is = null;
    private DataInputStream dis;
    private boolean isRun = true;
    private Socket socket = null;
    byte buff[]  = new byte[4096];
    private String rcvMsg;
    private int rcvLen;

    private final ModbusCfg modbusCfg;


    public TcpClient(String ip, int port, ModbusCfg modbusCfg){
        //this.serverIP  = "192.168.88.212";//测试时
        this.serverIP = ip;
        this.serverPort = port;
        this.modbusCfg = modbusCfg;
    }

    public void closeSelf(){
        isRun = false;
    }

    public void send(String msg){
        try{
            ByteBuffer wrBuf = ByteBuffer.allocate(4096);
            modbusCfg.SendPro(wrBuf, msg);
            //数据送出
            os.write(wrBuf.array(),0, wrBuf.limit());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void closeSocket(String rcvMsg)
    {
        try {
            os.close();
            is.close();
            dis.close();
            socket.close();
            Intent intent = new Intent();
            intent.setAction("tcpServerReceiver");
            intent.putExtra("tcpServerReceiver", rcvMsg);
            FuncTcpServer.context.sendBroadcast(intent);//将消息发送给主界面
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            socket = new Socket(serverIP,serverPort);
            socket.setSoTimeout(5000000);
            os = socket.getOutputStream();
            is = socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (isRun && !socket.isClosed() && !socket.isOutputShutdown()) {
            try {
                if ((rcvLen = is.read(buff)) != -1) {
                    String rcvMsg = "Rx: " + modbusCfg.RcvPro(buff, rcvLen);
                    Log.i(TAG, rcvMsg);
                    Intent intent = new Intent();
                    intent.setAction("tcpServerReceiver");
                    intent.putExtra("tcpServerReceiver", rcvMsg);
                    FuncTcpServer.context.sendBroadcast(intent);//将消息发送给主界面
                }
            } catch (IOException e) {
                closeSocket("超时已关闭，请重新连接!");
            }
        }
        closeSocket("与服务器的连接已关闭");
    }
}